package cn.findviewbydream.evil.app.websocket

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.socket.*
import java.util.*

/********************************************
 * 工程名：MealOrder
 * 包名：cn.findviewbydream.evil.app.websocket
 * 时间：16-12-25
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：WebSocket处理器 实现类
 ********************************************/
class WebSocketHandlerImpl : WebSocketHandler
{
    private val logger: Logger = LoggerFactory.getLogger(WebSocketHandlerImpl::class.java)

    companion object
    {
        /*保存当前正在连接用户id*/
        val users = ArrayList<WebSocketSession>()

        /**
         * 给所有在线用户发送消息
         */
        fun sendMessageToUsers(message: String)
        {
            users.filter { it.isOpen }.forEach { it.sendMessage(TextMessage(message)) }
        }

        fun sendMessageToUsers(message: Int)
        {
            users.filter { it.isOpen }.forEach { it.sendMessage(TextMessage("$message")) }
        }

        /**
         * 给某个用户发送消息
         */
        fun sendMessageToUser(userId: String, message: String)
        {
            for (user in users)
            {
                if (user.attributes["WEBSOCKET_USERID"] == userId)
                {
                    if (user.isOpen)
                        user.sendMessage(TextMessage(message))
                    break
                }
            }
        }
    }

    /**
     * 首次连接成功
     */
    override fun afterConnectionEstablished(session: WebSocketSession)
    {
        users.add(session)
        val userId = getSessionId(session)
        println("$userId 连接成功")
    }

    /**
     * 连接出错
     */
    override fun handleTransportError(session: WebSocketSession, throwable: Throwable)
    {
        if (session.isOpen)
            session.close()

        logger.info("${getSessionId(session)} 链接出错 ${throwable.message}，关闭链接......")
        users.remove(session)
    }

    /**
     * 连接关闭
     */
    override fun afterConnectionClosed(session: WebSocketSession, status: CloseStatus)
    {
        logger.info("${getSessionId(session)} 链接关闭......" + status.toString())
        users.remove(session)
    }

    /**
     * 支持部分信息？表示不知道什么意思
     */
    override fun supportsPartialMessages(): Boolean = false

    /**
     * 处理信息
     */
    override fun handleMessage(session: WebSocketSession, message: WebSocketMessage<*>)
    {
        logger.info("来自：${getSessionId(session)}" + message.payload.toString())

        sendMessageToUsers(message.payload.toString())
    }

    /**
     * 通过session获取id
     */
    private fun getSessionId(session: WebSocketSession): String
    {
        return session.attributes["WEBSOCKET_USERID"] as String
    }
}